package 创建型模式.原型;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassNameUser
 * @Description
 * @Author
 * @Date2021/11/18 20:45
 **/
public class User implements Cloneable,Serializable{


    /**
     * 姓名
     */
    private String name;
    /**
     * 电话
     */
    private String phone;
    /**
     * 拥有的物品
     */
    private List<String> have = new ArrayList<>();


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public List<String> getHave() {
        return have;
    }

    public void setHave(List<String> have) {
        this.have = have;
    }


    @Override
    protected User clone() {
        // 浅克隆
//        try {
//            return (User)super.clone();
//        } catch (CloneNotSupportedException e) {
//            e.printStackTrace();
//            return null;
//        }

        // 深克隆,需要实现序列化接口
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (User) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", have=" + have +
                '}';
    }
}
